#include <iostream>
#include <unordered_map>
#include <string>
#include <fstream>
#include "Log.hpp"

#define DEFAULT_CONF_PATH "./dict.txt"
#define DEFAULT_SEP ": "

class dictionary
{
private:
    bool load()
    {
        std::ifstream in(_conf_path);
        if(in.is_open() == false)
        {
            LOG(wzx::log_level::ERROR) << "open dictionary fill!!!";
            return false;
        }

        std::string line_buffer;
        const std::string sep = DEFAULT_SEP;
        while(std::getline(in, line_buffer))//getline()返回的是一个istream&对象, 但其重载了operator bool, 
        {                                   //如果除了goodbit以外的三个标志位([eofbit], badbit, failbit)任一被置位, 则返回false, 否则返回true

            if(line_buffer.empty())//读到空行
                continue;

            size_t pos = line_buffer.find(sep);
            if(pos == std::string::npos)//读到格式不对的行(standard fromat:> [key: value])
                continue;

            std::string key = line_buffer.substr(0, pos);
            std::string value = line_buffer.substr(pos + sep.size());
            _dict.emplace(key, value);
        }
        LOG(wzx::log_level::INFO) << "load success";
        return true;

    }

public:
    dictionary(const std::string& conf_path = DEFAULT_CONF_PATH)
        :_conf_path(conf_path)
    {
        while(!load())
        {
            std::cout << "please enter conf_path again :> ";
            std::cin >> _conf_path;
        }
    }

    std::string translate(const std::string& English)
    {
        auto it = _dict.find(English);
        if(it == _dict.end())
            return "unknown";
        return it->second;
    }


private:
    std::string _conf_path;//数据源的路径+文件名
    std::unordered_map<std::string, std::string> _dict;
};